import React, { useEffect, useState } from 'react';
import styles from './index.less';
import {
  Tabs,
  Spin,
  Button,
  Card,
  Row,
  Col,
  Select,
  InputNumber,
  DatePicker,
  message,
} from 'antd';
import common from '../../common';
import { VoucherTable } from '../../component';
const { TabPane } = Tabs;
import moment from 'moment';
import { history } from 'umi';
const SubjectEvent = {
  getAll: 'subject-getall',
  insert: 'voucher-insert',
  updateStatus: 'subject-update-status',
  getTopSort: 'voucher-gettopsort',
};
const initVoucherData = [
  {
    sort: 1, //排序key
    abstract: '', //描述
    subjectName: '',
    subjectCode: '',
    debtorAmount: '',
    lenderAmount: '',
    subjectDirection: null,
  },
  {
    sort: 2, //排序key
    abstract: '', //描述
    subjectName: '',
    subjectCode: '',
    debtorAmount: '',
    lenderAmount: '',
    subjectDirection: null,
  },
  {
    sort: 3, //排序key
    abstract: '', //描述
    subjectName: '',
    subjectCode: '',
    debtorAmount: '',
    lenderAmount: '',
    subjectDirection: null,
  },
  {
    sort: 4, //排序key
    abstract: '', //描述
    subjectName: '',
    subjectCode: '',
    debtorAmount: '',
    lenderAmount: '',
    subjectDirection: null,
  },
];
export default () => {
  const [subjectList, setSubjectList] = useState([]);
  const [sort, setSort] = useState(null);
  const [voucherDate, setVoucherDate] = useState(moment());
  const [voucherType, setVoucherType] = useState(1);
  useEffect(() => {
    common.commonEvent(SubjectEvent.getAll, setSubjectList, null);
    common.commonEvent(SubjectEvent.getTopSort, setSort, {
      voucherType: 1,
      voucherDate: moment().format('YYYY-MM-DD'),
    });
  }, []);
  let treedata = subjectList.map(item => {
    return {
      value: item.subjectCode,
      label: item.subjectName + '(' + item.subjectCode + ')',
      baseLabel: item.subjectName,
      subjectDirection: item.subjectDirection,
      children: item.children.map(cy => {
        return {
          value: cy.subjectCode,
          label: cy.subjectName + '(' + cy.subjectCode + ')',
          baseLabel: cy.subjectName,
          subjectDirection: cy.subjectDirection,
          children: cy.children.map(pp => {
            return {
              value: pp.subjectCode,
              label: pp.subjectName + '(' + pp.subjectCode + ')',
              baseLabel: pp.subjectName,
              subjectDirection: pp.subjectDirection,
            };
          }),
        };
      }),
    };
  });
  const [voucherData, setVoucherData] = useState([...initVoucherData]);
  let PacVoucherData = [...voucherData];
  useEffect(() => {
    PacVoucherData = [...voucherData];
  }, [voucherData]);
  const submitVoucher = () => {
    let debtorAmount = 0;
    let lenderAmount = 0;
    voucherData.forEach((value, index) => {
      if (value.debtorAmount) {
        debtorAmount += parseFloat(value.debtorAmount);
      }
      if (value.lenderAmount) {
        lenderAmount += parseFloat(value.lenderAmount);
      }
    });
    if (debtorAmount === 0 && lenderAmount === 0) {
      message.error('请填写相关数据后再保存！');
      return;
    }
    if (debtorAmount != lenderAmount) {
      message.error('借贷金额不一致！');
      return;
    } else {
      let pdetail = voucherData.filter((value, index) => {
        return value.subjectCode !== '';
      });
      console.log(pdetail);
      let postData = {
        voucherType: voucherType,
        voucherDate: voucherDate.format('YYYY-MM-DD'),
        borrow: debtorAmount, //借方累计金额
        loan: lenderAmount, //贷方累计金额
        voucherDetails: [...pdetail],
      };
      common.commonEvent(
        SubjectEvent.insert,
        res => {
          if (res.success) {
            clearVoucher();
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        },
        postData,
      );
    }
  };
  const clearVoucher = () => {
    setVoucherData([
      {
        sort: 1, //排序key
        abstract: '', //描述
        subjectName: '',
        subjectCode: '',
        debtorAmount: '',
        lenderAmount: '',
        subjectDirection: null,
      },
      {
        sort: 2, //排序key
        abstract: '', //描述
        subjectName: '',
        subjectCode: '',
        debtorAmount: '',
        lenderAmount: '',
        subjectDirection: null,
      },
      {
        sort: 3, //排序key
        abstract: '', //描述
        subjectName: '',
        subjectCode: '',
        debtorAmount: '',
        lenderAmount: '',
        subjectDirection: null,
      },
      {
        sort: 4, //排序key
        abstract: '', //描述
        subjectName: '',
        subjectCode: '',
        debtorAmount: '',
        lenderAmount: '',
        subjectDirection: null,
      },
    ]);
  };
  return (
    <Spin spinning={false}>
      <div className={styles.addvencherbox}>
        <div className={styles.header}>记账凭证</div>
        <Card title={null}>
          <div className={styles.addhandlerbox}>
            <Row gutter={[8, 8]}>
              <Col>
                <Button type="primary" size="small" onClick={submitVoucher}>
                  保存
                </Button>
              </Col>
              <Col>
                <Button type="primary" size="small">
                  打印
                </Button>
              </Col>
              <Col>
                <Button type="primary" size="small" onClick={clearVoucher}>
                  清空
                </Button>
              </Col>
              <Col>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => {
                    PacVoucherData = [...voucherData];
                    const cindex = PacVoucherData.length + 1;
                    console.log(cindex);
                    PacVoucherData.push({
                      sort: cindex, //排序key
                      abstract: '', //描述
                      subjectName: '',
                      subjectCode: '',
                      debtorAmount: '',
                      lenderAmount: '',
                      subjectDirection: null,
                    });
                    setVoucherData(PacVoucherData);
                  }}
                >
                  增加一行
                </Button>
              </Col>
              <Col>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => {
                    PacVoucherData = [...voucherData];
                    const cindex = PacVoucherData.length - 1;
                    console.log(PacVoucherData);
                    PacVoucherData.splice(cindex, 1);
                    console.log(PacVoucherData);
                    setVoucherData(PacVoucherData);
                  }}
                >
                  减少一行
                </Button>
              </Col>
            </Row>
            <Row gutter={[8, 8]}>
              <Col>
                <Select
                  value={voucherType}
                  size="small"
                  onChange={value => {
                    setVoucherType(value);
                  }}
                >
                  <Select.Option value={1}>记</Select.Option>
                  <Select.Option value={2}>收</Select.Option>
                  <Select.Option value={3}>付</Select.Option>
                  <Select.Option value={4}>转</Select.Option>
                </Select>
              </Col>
              <Col>
                <InputNumber
                  style={{ width: '50px' }}
                  size="small"
                  value={sort}
                  disabled={true}
                ></InputNumber>
                号
              </Col>
              <Col> 日期:</Col>
              <Col>
                <DatePicker
                  size="small"
                  defaultValue={voucherDate}
                  onChange={value => {
                    setVoucherDate(value.format('yyyy-MM-dd'));
                  }}
                />
              </Col>
            </Row>
            <Row style={{ marginLeft: 0 }} gutter={[8, 8]}>
              <VoucherTable
                subjectList={treedata}
                voucherData={voucherData}
                onVoucherChange={item => {
                  let rindex = 0;
                  PacVoucherData.forEach(c => {
                    if (c.sort == item.sort) {
                      PacVoucherData.splice(rindex, 1);
                      PacVoucherData.push(item);
                      PacVoucherData = PacVoucherData.sort((a, b) => {
                        return a.sort - b.sort;
                      });
                    }
                    rindex++;
                  });
                  setVoucherData(PacVoucherData);
                }}
              ></VoucherTable>
            </Row>
          </div>
        </Card>
      </div>
    </Spin>
  );
};
